# -*- coding: UTF-8 -*-

import datetime
import pandas as pd

from datasource.data_interface import DataInterface

'''
基金业绩数据, 并转换为DataFrame
Fund Performance - 基金业绩

基金业绩排行网址：http://fund.eastmoney.com/data/rankhandler.aspx
接口入参：
"op": "ph",  # ph-排行
"dt": "kf",  # kf-开放
"ft": "all",  # all-所有
"rs": "",
"gs": 0,
"sc": "zzf",  # 按哪一行排序  zzf-???
"st": "desc",
"sd": sd,  # sd-查询的开始日期 "2019 - 02 - 19"
"ed": ed,  # all-查询的结束日期 "2020 - 02 - 19"
"qdii": "",
"tabSubtype": ["", "", "", "", "", ""],
"pi": 1,  # pi-第几页
"pn": pn,  # pn-1页展示的条数
"dx": 1,
"v": 0.8367023148607453
'''


class InterfaceFundPerformance(object):

    def __init__(self, sd, ed, pn):
        self.url = 'http://fund.eastmoney.com/data/rankhandler.aspx'

        # 混合型基金，<=5000行数据，按自定义降序排列
        self.params = {
            "op": "ph",  # ph-排行
            "dt": "kf",  # kf-开放
            "ft": "hh",  # 基金类型， all-所有 hh-混合
            "rs": "",
            "gs": 0,
            "sc": "qjzf",  # 按哪一列排序， zzf-近一周，qjzf-按自定义排行
            "st": "desc",   # 降序， desc-降序
            "sd": sd,  # sd-查询的开始日期 "2019 - 02 - 19"
            "ed": ed,  # all-查询的结束日期 "2020 - 02 - 19"
            "qdii": "",
            "tabSubtype": ["", "", "", "", "", ""],
            "pi": 1,  # pi-第几页
            "pn": pn,  # pn-1页展示的条数
            "dx": 1,
            "v": 0.8367023148607453
        }


    def getdata_fundperformance(self):

        fp_ls = []

        # td = datetime.date.today()
        # sd = datetime.date(td.year - 1, '01', '01')
        # ed = datetime.date(td.year - 1, '12', '31')
        # pn = 5000
        # # sd = datetime.date(ed.year - 1, ed.month, ed.day)


        start_str = 'var rankData = '
        end_str = ';'
        keyname = 'datas'

        # | 基金代码 | 基金简称 | 基金类型 | 基金成立日期 | 近1年业绩 | 近2年业绩 | 近3年业绩 | 资金规模(亿) |

        cols = ["基金代码", "基金简称", "基金英文简称", "日期", "单位净值", "累计净值", "日增长率", "近1周", "近1月", "近3月", "近6月", "近1年业绩", "近2年业绩", "近3年业绩",
                "今年来", "成立来", "基金成立日期", "unkown1", "自定义", "手续费（原价）", "手续费", "折扣", "手续费", "unkown2", "unkown3"]

        ifp = DataInterface(self.url, self.params, start_str, end_str)
        ifp_datas = ifp.get_response(keyname)

        for dp_data in ifp_datas:
            ls_data = dp_data.split(',')
            fp_ls.append(ls_data)

        fp_dataframe = pd.DataFrame(fp_ls, index=list(range(1, len(fp_ls)+1)), columns=cols)

        return fp_dataframe


if __name__ == '__main__':

    sd = '2019-01-01'
    ed = '2019-12-31'
    pn = 20
    ifp = InterfaceFundPerformance(sd, ed, pn)
    fp_dataframe =ifp.getdata_fundperformance()
    df = fp_dataframe.loc[:, ["基金代码", "基金简称", "基金成立日期", "近1年业绩", "近2年业绩", "近3年业绩"]]
    df["基金成立日期"] = pd.to_datetime(df["基金成立日期"])
    print(df.dtypes)
    print("-------------------------------------------------")
    df.sort_values(by="基金成立日期", inplace=True, ascending=False)
    print(df)
    td = datetime.date.today()
    date1 = datetime.date(td.year - 3, 1, 1)

    for datestr in df["基金成立日期"]:
        # 成立大于3年的
        if datestr < date1:
            print(datestr)
    print("----------------------------------------------------")

    for index, row in df.iterrows():
        if row["基金成立日期"] > date1:
            df.drop(index=index, inplace=True)

    # df.shape[0] 等同于 len(df)，返回行数；df.shape[1] 返回列数
    strdump = '混合型,' * df.shape[0]
    strdump = strdump.rstrip(',')
    strls = strdump.split(',')
    df["基金类型"] = strls
    print(df)
    # 转换列数据的类型
    df["近1年业绩"] = df["近1年业绩"].astype("float")
    df["近2年业绩"] = df["近2年业绩"].astype("float")
    df["近3年业绩"] = df["近3年业绩"].astype("float")
    # df["自定义"].astype("float")
    print(df.dtypes)
    print("----------------------------------------------------")
    print(df.info)
